package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.search.pojos.SearchArticleVo;
import com.heima.search.service.HistorySearchService;
import com.heima.search.service.SearchService;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author xiaquanen
 * @version 1.0
 * @project heima-leadnews
 * @date 2024/7/29 16:27:05
 */
@Service
@Slf4j
public class SearchServiceImpl implements SearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private HistorySearchService historySearchService;

    /**
     * 查询
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) {
        try {
            if(StringUtils.isNotEmpty(dto.getSearchWords()))
            //添加历史搜索记录
                historySearchService.saveHistory(dto.getSearchWords(), AppThreadLocalUtil.getUserId());

            SearchRequest request = new SearchRequest("app_info_article");
            //拼接查询条件
            //所有的条件都在source之后
            SearchSourceBuilder source = request.source();
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            boolQueryBuilder.must(QueryBuilders.multiMatchQuery(dto.getSearchWords(), "title", "content"));
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("publishTime").lte(dto.getMinBehotTime()));
            source.query(boolQueryBuilder);
            source.from(dto.getFromIndex());
            source.size(dto.getPageSize());
            source.sort("publishTime", SortOrder.DESC);
            source.highlighter(new HighlightBuilder().field("title").preTags("<font style='color: red; font-size: inherit;'>").postTags("</font>"));
            SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            log.info("查询到的数据"+search);
            //封装返回数据
            SearchHit[] hits = search.getHits().getHits();
            List<JSONObject> list=new ArrayList<>();
            for (SearchHit hit : hits) {
                String sourceAsString = hit.getSourceAsString();
                JSONObject jsonObject = JSONObject.parseObject(sourceAsString);
                list.add(jsonObject);
                //处理高亮字段
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if(!highlightFields.isEmpty())
                {
                    String s = highlightFields.get("title").getFragments()[0].toString();
                    jsonObject.put("h_title",s);
                }else
                {
                    jsonObject.put("h_title",jsonObject.get("title"));
                }
            }
            return ResponseResult.okResult(list);
        }catch (Exception e)
        {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
    }

    /**
     * 更新或者添加索引
     *
     * @param searchArticleVo
     */
    @Override
    public void addOrUpdate(SearchArticleVo searchArticleVo) {
        try {
            //先删除文档
            deleteDoc(searchArticleVo.getId());
            //不管更新还是修改一律视为添加
            IndexRequest indexRequest = new IndexRequest("app_info_article").id(String.valueOf(searchArticleVo.getId()));
            // 这里可以利用实体转JSON的形式来生成json
            indexRequest.source(JSON.toJSONString(searchArticleVo), XContentType.JSON);
            restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
                } catch (Exception e) {
            e.printStackTrace();
            ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
    }
    /**
     * 先删除文档
     *
     * @param id
     */
    public void deleteDoc(Long id) {
        try {
        DeleteRequest request = new DeleteRequest("app_info_article").id(String.valueOf(id));
            restHighLevelClient.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("索引库中没有该数据");
        }
    }
}
